/*global Ext, Portal */
Ext.apply(Portal, {
    oCenterRegion: null,
    oNorthRegion: null
});

var glob;

//se creaza namespace-ul main
Ext.ns('Portal.main');
//in namespace-ul main se creaza un set de functii care au rol de a porni un modul nou ( user, corector, etc  )
//fiecare functie din namespace va apela o functie corespunzatoare. Pentru a avea mai mult control asupra functiei din modul  (functia de initializare) am preferat sa creez un set de functii in namespace.
Ext.apply(Portal.main, {

    //functie de schimabre parola
    fnChangePass: function() {
        Ext.MessageBox.prompt('Schimbare Parola', 'Parola :',
                function(btn, text) {
                    if (btn == 'ok') {
                        Ext.Ajax.request({
                            url: 'user/addPass/' + Math.random(),
                            params: {
                                pass: text
                            }
                        });
                    }
                });
    },
    //porneste modulul de meniuri
    fnAddMenuObjects: function() {
        try {
            Portal.menuObject.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    //porneste modulul corector
    fnOpenCorrectorScreen: function() {
        try {
            Portal.correctorScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    //porneste modulul de modificare a unui contact
    fnOpenContactScreen: function(contact) {
        Portal.contactScreen.exec(contact);
        try {
            // Portal.contactScreen.exec(contact);
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    //porneste modulul de import
    fnOpenImportScreen: function() {
        try {
            Portal.importScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    //porneste modulul de administrare imagini mailer
    fnOpenImageScreen: function() {
        try {
            Portal.imageScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    fnOpenTemplateScreen: function() {
        try {
            Portal.templateScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    //porneste modulul de administrare atasamente mailer
    fnOpenAttachScreen: function() {
        try {
            Portal.attachScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    //porneste modulul de administrare mailere
    fnOpenMailerScreen: function() {
        try {
            Portal.mailerScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },
    fnOpenMailerTaskScreen: function() {
        try {
            Portal.mailerTaskScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },

    fnOpenCampaignScreen: function() {
        try {
            Portal.campaignScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    },

    //porneste modulul de raport
    fnOpenSupportScreen: function() {
        try {
            Portal.supportScreen.exec();
        }
        catch(e) {
            Portal.events.throwError(e);
        }
    }
});

Ext.ns('Portal.events');


//creare seturi functii mesaje
Ext.apply(Portal.events, {
    /**
     * Usage: Portal.events.throwError('Error description here!');
     * @param {String} msg
     */
    throwError: function(msg) {
        Ext.ux.PortalToast.msg({
            title: 'Eroare',
            iconCls: 'icon-fugue-minus-shield'
        },
                '{0}', msg);
    },

    throwInformation: function(msg) {
        Ext.ux.PortalToast.msg({
            title: 'Informatie',
            iconCls: 'icon-information'
        },
                '{0}', msg);
    },
    throwWarning: function(msg) {
        Ext.ux.PortalToast.msg({
            title: 'Avertisment',
            iconCls: 'icon-error'
        },
                '{0}', msg);
    }
});

//creare seturi functii de suprascriu functiile AJAX a.i. daca sa se afiseze mesaje ( confirmari , erori) pe interfata utilizatorului )
Ext.apply(Portal.events, {

    beforeRequest: function(conn, response, options) {
        //console.log("inainte de request");
        Ext.getCmp("logmessages").el.mask("Loading..");
    },

    requestException: function(conn, response, options) {
        Ext.getCmp("logmessages").el.unmask();
        //console.log("problema");
        Portal.events.parseJsonResponse(conn, response, options, true);
    },

    requestComplete: function(conn, response, options) {
        //console.log("request terminat");
        Ext.getCmp("logmessages").el.unmask();
        Portal.events.parseJsonResponse(conn, response, options);
    },

    parseJsonResponse: function(conn, response, options, exception) {
        // case there is an exception throw an error
        try {
            if (exception !== undefined) {
                //console.log(response);
                Portal.events.throwError('[status: ' + response.status + '] ' + response.statusText);
                //return;
            }
        }
        catch(e) {
        }

        try {
            // daca raspunsul este json clasic
            if ((   response.responseText.search(/\{"error":/i) !== -1    ) || (    response.responseText.search(/\{'error':/i) !== -1  )) {
                //console.info('DO DECODE');
                var oResponse = Ext.decode(response.responseText);

                if (oResponse.error !== undefined) {
                    if (( oResponse.error === true  ) || ( oResponse.error == 'true'  )) {
                        Portal.events.throwError('[' + oResponse.type + '] ' + oResponse.description);
                        if (oResponse.type == 'nosession') {
                            //Ext.MessageBox.alert('Status', 'Sesiunea a expirat.. ');
                        }
                        return;
                    }
                    else if ((oResponse.error === false  ) || (oResponse.error == 'false')) {

                        if (oResponse.type != 'silent') { // silent response, do not echo
                            if (oResponse.description) {
                                Portal.events.throwInformation(oResponse.description);
                            }
                            return;
                        }
                    }
                }
            }            
        }
        catch(er) {
            //console.error(e);
        }

    }
});

// adaugare functii pentru preluare mesaje ajax
Ext.Ajax.on('beforerequest', Portal.events.beforeRequest, this);
Ext.Ajax.on('requestcomplete', Portal.events.requestComplete, this);
Ext.Ajax.on('requestexception', Portal.events.requestException, this);

Ext.apply(Portal.main, {
    exec: function() {

        var oNorthRegion = {
            region: 'north',
            html: '<div></div>',
            tbar: [
                {
                    xtype: 'buttongroup',
                    columns: 4,
                    items: [
                        {
                            xtype: 'tbbutton',
                            text: 'Setari',
                            iconCls: 'icon-fugue-globe',
                            menu: [
                                {
                                    text: 'Schimbare parola',
                                    iconCls: 'icon-fugue-key',
                                    handler: Portal.main.fnChangePass
                                },
                                {
                                    //cand se selecteaza un design atunci se trimite un call ajax cate server si se seteaza in baza de date , la user designul selectat..schimbarea de design se face automat , pluginul Ext.ux.ThemeCombo.js realizeaza acest lucru ( vezi main.php 61)
                                    xtype: 'themecombo',
                                    listeners: {
                                        'select': function() {
                                            Ext.Ajax.request({
                                                url: 'user/setStyle',
                                                params: {
                                                    style: this.getValue()
                                                }
                                            });
                                        }
                                    }
                                },
                                {
                                    iconCls: 'icon-fugue-smiley-cool',
                                    text: 'Semnatura',
                                    handler: Portal.signScreen.exec
                                }
                            ]
                        },
                        {
                            xtype: "tbbutton",
                            iconCls: 'icon-group',
                            text: 'Baza Date',
                            handler: Portal.bazaScreen.exec
                        },
                        {
                            xtype: "tbbutton",
                            iconCls: 'icon-cog',
                            text: 'Campanii',
                            handler: Portal.main.fnOpenCampaignScreen
                        },
                        /*{
                         text: "Manual",
                         iconCls: 'icon-book',
                         handler: function() {
                         window.open("resources/manual/Manual_CRM.doc");
                         }
                         },*/
                        {
                            text: 'Follow Up',
                            iconCls: 'icon-telephone',
                            menu: new Ext.menu.Menu({
                                items: [
                                    {
                                        iconCls: 'icon-newspaper',
                                        text: 'Status',
                                        handler: Portal.teleStatusScreen.exec
                                    },
                                    {
                                        iconCls: 'icon-fugue-question-frame',
                                        text: 'Intrebari',
                                        handler: Portal.teleQuestionScreen.exec
                                    },
                                    {
                                        iconCls: 'icon-fugue-question-frame',
                                        text: 'Intrebari cu raspuns liber',
                                        handler: Portal.teleQuestionFreeScreen.exec
                                    },
                                    {
                                        iconCls: 'icon-fugue-question-frame',
                                        text: 'Campuri custom',
                                        handler: Portal.teleCustomScreen.exec
                                    },
                                    {
                                        iconCls: 'icon-telephone',
                                        text: 'Follow Up',
                                        handler: Portal.teleScreen.exec
                                    }
                                ]
                            })
                        },

                        {
                            text: 'Operatii',
                            iconCls: 'icon-package-add',
                            tooltip: 'Mici formulare pentru a adauga orase, judete, functii, domenii s.a.m.d',
                            menu: new Ext.menu.Menu({
                                id: 'menuObjects',
                                style: {
                                    overflow: 'visible' // For the Combo popup
                                }
                            })
                        },
                        {
                            text: 'Rapoarte',
                            iconCls: 'icon-fugue-chart',
                            menu: new Ext.menu.Menu({
                                items: [
                                    {
                                        iconCls: 'icon-user-gray',
                                        text: 'Nr. contacte lucrate / zi',
                                        handler: function() {
                                            window.location.href = 'raport/dayContact/';
                                        }
                                    },
                                    {
                                        text: 'Follow Up',
                                        iconCls: 'icon-fugue-table-excel',
                                        handler:  Portal.report.getTelemarketing
                                    }/*,
                                    {
                                        text: 'Link-uri Campanii',
                                        iconCls: 'icon-fugue-table-excel',
                                        handler:  Portal.report.getCampanieLinkuri
                                    }  */
                                ]
                            })
                        },
                        {
                            text: 'Mailer',
                            iconCls: 'icon-fugue-mail-open-image',
                            menu: new Ext.menu.Menu({
                                items: [
                                    {
                                        text: 'Setari Mailer',
                                        iconCls: 'icon-clock-edit',
                                        handler: Portal.main.fnOpenMailerScreen
                                    },
                                    {
                                        text: 'Programari Mailer',
                                        iconCls: 'icon-clock-play',
                                        handler: Portal.main.fnOpenMailerTaskScreen
                                    }
                                ]
                            })
                        }
                    ]
                },
                {
                    xtype: "buttongroup",
                    columns: 2,
                    hidden :  (Portal.user_role == 'user' ) ,
                    items: [
                      /*  {
                            xtype: 'tbbutton',
                            iconCls: 'icon-pill',
                            text: 'Corector',
                            handler: Portal.main.fnOpenCorrectorScreen
                        },*/
                        {
                            text: 'Administrare',
                            xtype: 'tbbutton',
                            iconCls: 'icon-fugue-user-black',
                            menu: new Ext.menu.Menu({
                                //style: {overflow: 'visible' },
                                //cand se va incarca Portal.main.fnAddMenuObjects se vor aduce elemente in acest meniu ( se va cauta dupa id)
                                items: [
                                    {
                                        iconCls: 'icon-group-key',
                                        text: 'Useri',
                                        handler: Portal.userScreen.exec
                                    }  ,
                                    {
                                        iconCls: 'icon-vcard',
                                        text: 'Logo MTP',
                                        handler: Portal.logoScreen.exec
                                    }
                                ]
                            })
                        },
                       /* {
                            iconCls: 'icon-fugue-smiley-twist',
                            text: 'Import',
                            handler: Portal.main.fnOpenImportScreen
                        } ,*/
                        {
                            xtype: 'tbbutton',
                            iconCls: 'icon-fugue-tick-shield',
                            text: 'Suport',
                            //hidden : true ,
                            handler: Portal.main.fnOpenSupportScreen
                        }
                    ]
                },
                {
                    xtype: "panel",
                    width: 450,
                    height: 40,
                    id: "logmessages",
                    cls: "logmessages",
                    frame: true,
                    autoScroll: true,
                    autoHeight: true
                },
                '->',
                {
                    text: 'Logout',
                    iconCls: 'icon-user-go',
                    handler: function() {
                        window.location = 'main/do_logout';
                    }
                }
            ]
        };

        var oCenterRegion = {
            region: 'center',
            xtype: 'tabpanel',
            activeItem: 0,
            enableTabScroll: true,
            resizeTabs: true,
            minTabWidth: 100,
            hideMode: "offsets",
            deferredRender: false,
            defaults: {
                closable: true
            },
            items: [
                {
                    html: "User Raport ..work in progress",
                    title: "Welcome"
                }
            ],
            //se pune conditie la stergerea unui tab si anume la inchiderea unui tab de contact
            //daca se deschide un tab de contact dar nu se salveaza , la inchidere tab apare o fereastra de confirmare
            // in fiecare contact se pune un obiect cu id "fpContact_saved_"+id in care se seteaza daca contactul a fost sau nu salvat vezi contact.js
            listeners: {
                "beforeremove": function(container, component) {

                    var idComp = component.id;
                    id = idComp.substr(8, id.length);

                    if (component.findById("fpContact_saved_" + id)) {
                        var saved = component.findById("fpContact_saved_" + id).getValue();
                        if (saved == "0") {
                            if (container.removeConfirmed) {
                                delete container.removeConfirmed;
                                return true;
                            }
                            Ext.Msg.confirm('Confirmare', 'Sigur doriti sa inchideti ?',
                                    function(btn) {
                                        if (btn == 'yes') {
                                            container.removeConfirmed = true;
                                            container.remove(component);
                                        }
                                    });
                            return false;
                        }
                        /*if (saved == "1") {
                         return true;
                         }*/
                    }
                    return true;
                }
            }
        };

        var oAppViewport = new Ext.Viewport({
            layout: 'border',
            items: [oNorthRegion, oCenterRegion],
            renderTo: Ext.getBody()
        });

        Portal.oNorthRegion = oAppViewport.getComponent(0);
        Portal.oCenterRegion = oAppViewport.getComponent(1);
    }
});
